package it.fuesi.expired.api.controllers;

import java.util.Date;

import it.fuesi.expired.adapters.mongo.MongoAdapterQuery;
import it.fuesi.expired.api.ItemService;
import it.fuesi.expired.api.controllers.base.ACrudController;
import it.fuesi.expired.model.FindParameters;
import it.fuesi.expired.model.Item;
import it.fuesi.expired.model.base.ErrorModel;
import it.fuesi.expired.model.base.ModelCollection;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;



@Controller
public class ItemController extends ACrudController<Item> implements ItemService{

	@RequestMapping(method = RequestMethod.GET, value = BASE_URI)
	@ResponseBody()
	public ModelCollection<Item> getAll() throws Exception{
		return super.getAll();
	}
	
	@RequestMapping(method = RequestMethod.GET, value = FIND_URI)
	@ResponseBody()
	public ModelCollection<Item> find(FindParameters params) throws Exception{
		final MongoAdapterQuery query = MongoAdapterQuery.build("expireDate", MongoAdapterQuery.build(params.isExpired() ? "$lte" : "$gte", new Date()));
		
		return adapter.openSession().find(Item.class, query);
	}
	
	
	@RequestMapping(method = RequestMethod.GET, value = BASE_URI + "/{_id}")
	@ResponseBody
	public Item get(@PathVariable String _id) throws Exception{
		return super.get(_id);
	}
	
	@RequestMapping(method=RequestMethod.POST, value=BASE_URI)
	@ResponseBody
	public Item add(@RequestBody Item item) throws Exception{
		return super.add(item);
	}
	
	@RequestMapping(method=RequestMethod.PUT, value=BASE_URI)
	@ResponseBody
	public Item update(@RequestBody Item item) throws Exception{
		return super.update(item);
	}
	
	@RequestMapping(method = RequestMethod.DELETE, value = BASE_URI + "/{_id}")
	@ResponseBody
	public ErrorModel delete(@PathVariable String _id) throws Exception{
		return super.delete(_id);
	}
	
	@RequestMapping(method = RequestMethod.DELETE, value = BASE_URI)
	@ResponseBody
	public ErrorModel deleteAll() throws Exception{
		return super.deleteAll();
	}
	
}
